package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;

    @RequestMapping(value = "/list",name = "展示购销合同下货物列表数据")
    public String findAll(String contractId,
                          @RequestParam(value ="page",defaultValue = "1") Integer pageNumber,
                          @RequestParam(value ="size",defaultValue = "10")  Integer pageSize){


//        查询货物数据  select * from co_contract_product where contract_id=?
        ContractProductExample example = new ContractProductExample();
        example.createCriteria().andContractIdEqualTo(contractId);
        PageInfo pageInfo = contractProductService.findAll(example, pageNumber, pageSize);
        request.setAttribute("page",pageInfo);
//        查询生产货物的工厂 select * from co_factory where ctype='货物'
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

//        当前合同的id
        request.setAttribute("contractId",contractId);

        return "cargo/product/product-list";
    }


    @RequestMapping(value = "/toAdd",name = "进入到新增购销合同页面")
    public String toAdd(){

        return "cargo/contract/contract-add";
    }


    @RequestMapping(value = "/toUpdate",name = "进入到修改购销合同下货物页面")
    public String toUpdate(String id){  // 货物id
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);

        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);


        return "cargo/product/product-update";
    }

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(value = "/edit" ,name = "保存购销合同下货物数据")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto ){
//        把图片上传到七牛云
        String productImage = null;
        try {
            productImage = fileUploadUtil.upload(productPhoto);
            contractProduct.setProductImage(productImage);
        } catch (Exception e) {

        }

        if(StringUtils.isEmpty(contractProduct.getId())){
            contractProduct.setId(UUID.randomUUID().toString());
            contractProduct.setCompanyId(getCompanyId());
            contractProduct.setCompanyName(getCompanyName());
            contractProductService.save(contractProduct);
        }else {
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }

    @RequestMapping(value = "/delete" ,name = "删除购销合同下货物数据")
    public String delete(String id,String contractId){
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

    @RequestMapping(value = "/toImport" ,name = "进入批量上传货物页面")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "/cargo/product/product-import";
    }

/*    @RequestMapping(value = "/import" ,name = "保存批量上传货物方法")
    public String importXLS(String contractId,MultipartFile file) throws Exception{
//        解析excel 保存数据
        //        读取一个工作薄。里面是有内容的
        Workbook workbook  = new XSSFWorkbook(file.getInputStream());
//        获取sheet
        Sheet sheet = workbook.getSheetAt(0);

        int lastRowIndex = sheet.getLastRowNum();

        List<ContractProduct> list = new ArrayList<>();

        for (int i = 1; i <=lastRowIndex; i++) {

//        生产厂家	货号	数量	包装单位(PCS/SETS)	装率	箱数	单价	货物描述	要求
            Row row = sheet.getRow(i);

            ContractProduct contractProduct = new ContractProduct();
            String factoryName = row.getCell(1).getStringCellValue();
            contractProduct.setFactoryName(factoryName);

            String productNo = row.getCell(2).getStringCellValue();
            contractProduct.setProductNo(productNo);

            Integer cnumber = ((Double)row.getCell(3).getNumericCellValue()).intValue();
            contractProduct.setCnumber(cnumber);

            String packingUnit = row.getCell(4).getStringCellValue();
            contractProduct.setPackingUnit(packingUnit);

            String loadingRate =((Double) row.getCell(5).getNumericCellValue()).toString();
            contractProduct.setLoadingRate(loadingRate);

            Integer boxNum = ((Double)row.getCell(6).getNumericCellValue()).intValue();
            contractProduct.setBoxNum(boxNum);

            Double price = row.getCell(7).getNumericCellValue();
            contractProduct.setPrice(price);

            String productDesc = row.getCell(8).getStringCellValue();
            contractProduct.setProductDesc(productDesc);

            String productRequest = row.getCell(9).getStringCellValue();
            contractProduct.setProductRequest(productRequest);


            contractProduct.setId(UUID.randomUUID().toString());
            contractProduct.setContractId(contractId);

            list.add(contractProduct);
        }

        contractProductService.saveList(list);

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }*/

    @RequestMapping(value = "/import" ,name = "保存批量上传货物方法")
    public String importXLS(String contractId,MultipartFile file) throws Exception{

        List<ContractProduct> objectList = EasyExcel.read(file.getInputStream()). // 读取上传的文件
                head(ContractProduct.class) //指定读取内容的类型
                .sheet(0)  // 指定要读取的sheet
                .doReadSync();//把读取到的结果转化成ContractProduct的集合

        for (ContractProduct contractProduct : objectList) {
            contractProduct.setId(UUID.randomUUID().toString());
            contractProduct.setContractId(contractId);
        }

        contractProductService.saveList(objectList);

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

}
